package kz.pompei.ifacer.main;

import java.awt.Component;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFrame;

import kz.pompei.ifacer.conf.Config;
import kz.pompei.ifacer.grot.GrotPanel;
import kz.pompei.ifacer.main.align.AlignFrame;
import kz.pompei.ifacer.util.Handler;

public class MainFrame extends JFrame {
  private final Config mainConfig = new Config(new File(System.getProperty("user.home")
      + "/.ifacer/MainConfig.conf"));
  
  public MainFrame() throws Exception {
    new SizeLocationSaver(this, "MainFrame", mainConfig, 100, 100, 800, 600, WindowState.NORMAL);
    
    setTitle("Интерфейсер");
    
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    
    final AlignFrame alignFrame = new AlignFrame(mainConfig, this);
    
    final KeyManager keyManager = new KeyManager();
    final MainFramePanel mainFramePanel = new MainFramePanel(keyManager, alignFrame);
    setContentPane(mainFramePanel);
    
    KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    kfm.addKeyEventDispatcher(new KeyEventDispatcher() {
      @Override
      public boolean dispatchKeyEvent(KeyEvent e) {
        if (e.getID() == KeyEvent.KEY_PRESSED) {
          Component com = e.getComponent();
          
          while (com != null) {
            if (com instanceof JDialog) return false;
            if ("BottomToolBar".equals(com.getName())) return false;
            com = com.getParent();
          }
          
          return keyManager.dispatch(e);
        }
        return false;
      }
    });
    
    restoreFiles(mainFramePanel);
    
    addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
        for (GrotPanel grot : mainFramePanel.grotTabPanel.getGrotList()) {
          if (!grot.canClose()) return;
        }
        dispose();
        alignFrame.dispose();
      }
    });
    
  }
  
  private List<File> lastSavedWorkingFiles = new ArrayList<>();
  private int lastSavedSelectedIndex;
  
  private void restoreFiles(final MainFramePanel mainFramePanel) throws Exception {
    int fileCount = mainConfig.getInt("FileCount", 0);
    for (int i = 0; i < fileCount; i++) {
      File file = new File(mainConfig.get("WorkingFile" + i));
      if (file.exists()) {
        mainFramePanel.grotTabPanel.openFile(file);
        lastSavedWorkingFiles.add(file);
      }
    }
    
    {
      int selIndex = mainConfig.getInt("SelectedIndex", 0);
      while (selIndex > 0) {
        try {
          Component com = mainFramePanel.grotTabPanel.getComponentAt(selIndex);
          if (com instanceof GrotPanel) break;
        } catch (IndexOutOfBoundsException e) {}
        selIndex--;
      }
      mainFramePanel.grotTabPanel.setSelectedIndex(lastSavedSelectedIndex = selIndex);
    }
    
    mainFramePanel.grotTabPanel.updates.add(new Handler() {
      @Override
      public void handle() throws Exception {
        int tabCount = mainFramePanel.grotTabPanel.getTabCount();
        List<File> files = new ArrayList<>();
        for (int i = 0; i < tabCount; i++) {
          Component com = mainFramePanel.grotTabPanel.getComponentAt(i);
          if (com instanceof GrotPanel) {
            GrotPanel grot = (GrotPanel)com;
            if (grot.workingFile != null && grot.workingFile.exists()) {
              files.add(grot.workingFile);
            }
          }
        }
        
        if (files.equals(lastSavedWorkingFiles)
            && lastSavedSelectedIndex == mainFramePanel.grotTabPanel.getSelectedIndex()) {
          return;
        }
        
        mainConfig.setInt("FileCount", files.size());
        for (int i = 0, C = files.size(); i < C; i++) {
          mainConfig.set("WorkingFile" + i, files.get(i).getAbsolutePath());
        }
        
        lastSavedWorkingFiles = files;
        
        mainConfig.setInt("SelectedIndex",
            lastSavedSelectedIndex = mainFramePanel.grotTabPanel.getSelectedIndex());
        
        mainConfig.write();
      }
    });
    
    mainFramePanel.grotTabPanel.updates.fire();
  }
}
